
import { Post, Get, Prefix } from 'egg-shell-decorators';
import BaseController from './base';
import * as Sequelize from 'sequelize';

@Prefix('/')
export default class HomeController extends BaseController {

  @Get('')
  public async index({ request: { query } }) {
    const { ctx } = this;

    const { limit = 10, offset = 0, typeId = 0 } = query;

    const categorys = await ctx.service.category.getList({
      limit: 100,
      offset: 0,
    });


    let options = {};
    console.log(typeId);
    if (typeId !== 0) {
      options = {
        categoryId: {
          [Sequelize.Op.eq]: typeId,
        },

      };
    }


    const list = await ctx.service.article.getList({
      limit: parseInt(limit),
      offset: parseInt(offset),
      opt: options,
    });


    await ctx.render('home/index.html', { cates: categorys.rows, newslist: list.rows });
  }


  @Get('detail')
  public async detail({ request: { query } }) {
    const { ctx } = this;
    const { id } = query;
    const categorys = await ctx.service.category.getList({
      limit: 100,
      offset: 0,
    });


    const item = await ctx.service.article.get(parseInt(id));
    await ctx.render('home/detail.html', { cates: categorys.rows, mod: item });

  }


  @Get('aaaa')
  public async indexss() {
    const { ctx } = this;
    const users = await ctx.service.user.getUserList();
    console.log(users);
    await ctx.render('news/list.tpl', { list: users });
  }

  @Get('bbbb')
  public async getUserToken() {
    const c = { ccc: 'ccc' };
    this.success(c);
  }

  @Get('/bbbbb')
  public async getUserTokenb() {

    this.success('111111111111111');
  }


  @Post('/cccc')
  public async list() {
    const { ctx, app } = this;
    const pageSize = app.config.news.pageSize;
    const page = parseInt(ctx.query.page, 10) || 1;

    const idList = await ctx.service.news.getTopStories(page);

    // get itemInfo parallel
    const newsList = await Promise.all(idList.map(id => ctx.service.news.getItem(id)));
    await ctx.render('news/list.tpl', { list: newsList, page, pageSize });
  }

  @Get('/eeeee')
  public async detailq() {
    const { ctx } = this;
    const id = ctx.params.id;
    const newsInfo = await ctx.service.news.getItem(id);
    // get comment parallel
    const commentList = await Promise.all(newsInfo.kids.map(_id => ctx.service.news.getItem(_id)));
    await ctx.render('news/detail.tpl', { item: newsInfo, comments: commentList });
  }

  @Get('/fffff')
  public async user222() {
    const { ctx } = this;
    const id = ctx.params.id;
    const userInfo = await ctx.service.news.getUser(id);
    await ctx.render('news/user.tpl', { user: userInfo });
  }


}
